import json
import os
import argparse
os.environ["GIT_PYTHON_REFRESH"] = "quiet"
import logging
from urllib.parse import quote
from git import Repo
from git_operate import GitRepository
from constants import *
from syn_update_gitea import RequestURL

logger = logging.getLogger()
logging.basicConfig(level=logging.DEBUG,
                    filemode='a',
                    format='%(asctime)s [%(levelname)-5s] %(threadName)13s (%(module)s:%(funcName)s:%(lineno)d) - %(message)s'
                    )


class Download:
    """
    下载代码类
    """

    def __init__(self, url, username, password, dest_path, branch='master'):
        self.url = url.strip()
        self.username = username.strip()
        self.password = password.strip()
        self.dest_path = dest_path.strip().replace('\\', '/')
        self.branch = branch

    def start(self):
        logger.info('start download {0},{2} to {1}'.format(self.url, self.dest_path, self.branch))
        GitDownload(self.url, self.username, self.password, self.dest_path, self.branch).download()
        logger.info('end download {0} to {1}'.format(self.url, self.dest_path))


class GitDownload:

    def __init__(self, url: str, username: str, password: str, dest_path: str, branch: str):
        self.url = url
        self.username = quote(username)
        self.password = quote(password)
        self.dest_path = dest_path
        self.branch = branch

    def download(self):
        if self.url.startswith('http://'):
            url = 'http://' + self.username + ':' + self.password + '@' + self.url[7:]
        elif self.url.startswith('https://'):
            url = 'https://' + self.username + ':' + self.password + '@' + self.url[8:]
        else:
            raise Exception('not support url for ' + self.url)
        logger.debug('download url {0}'.format(url))
        self._clone_repo(url, self.dest_path, self.branch)

    def _clone_repo(self, url: str, path: str, branch: str):

        Repo.clone_from(url=url, to_path=path, branch=branch, env=os.environ)

class Synchronous():
    def __init__(self):
        pass


    def empty_old(self):
        # 清空分支
        remove_code = os.system("rm -rf {}/*".format(GITLAB_DIR))
        if remove_code != 0:
            return False
        return True

    def cp_gitea_to_gitlab(self):
        # 复制gitea master分支代码至gitlab structure_test分支
        cp_code = os.system("cp -rf {}/* {}/".format(GITEA_DIR, GITLAB_DIR))
        os.system("rm {}/synchronous_update.*".format(GITLAB_DIR))
        if cp_code != 0:
            return False
        return True

    def req_url(self):
        # 请求测试函数
        json_data = {
            "projectId": 113,
            "caseBranch": "master",
            "pageBranch": "master",
            "libBranch": "structure_test",
            "taskCmd": "-t mysql_demo",
            "notify": {
                "mode": 0,
                "instNotifies": None,
                "notifyPercent": 101
            }
        }
        post_text, flag = RequestURL.post_url_data(json_data, retry_time=10)
        if not flag:
            logger.error("启动执行测试用例失败！")
            return False
        post_data = json.loads(post_text)
        projectInstanceId = post_data["data"]["projectInstanceId"]
        logger.info("projectInstanceId为：{}".format(projectInstanceId))
        runState, flag = RequestURL.get_url_data(retry_time=60, projectInstanceId=projectInstanceId)
        if not flag:
            logger.error("测试用例执行失败！")
            return False
        if runState == 2:
            return True
        else:
            return False


    def run(self):
        branch_name = "structure_test"
        # 初始化git对象，拉取gitlab代码
        logger.info("初始化git对象，拉取gitlab代码")
        repo = GitRepository(GITLAB_DIR, GITLAB_URL)
        logger.info("拉取gitlab代码成功")
        branch_list = repo.branches()
        logger.info("存在分支：{}".format(branch_list))
        # 切换分支
        logger.info("切换至{}分支".format(branch_name))
        repo.change_to_branch(branch_name)
        logger.info("切换至{}分支成功".format(branch_name))
        repo.pull(GITLAB_TOKEN)
        # 清空分支
        logger.info("清空{}分支".format(branch_name))
        remove_code = self.empty_old()
        if not remove_code:
            raise Exception("清空旧分支失败！")
        logger.info("清空{}分支成功".format(branch_name))
        # 复制gitea master分支代码至gitlab structure_test分支
        logger.info("复制gitea master分支代码至gitlab {}分支".format(branch_name))
        cp_code = self.cp_gitea_to_gitlab()
        if not cp_code:
            raise Exception("复制gitea master分支代码至gitlab {}分支失败！".format(branch_name))
        logger.info("复制gitea master分支代码至gitlab {}分支成功！".format(branch_name))
        logger.info("开始推送到{}分支".format(branch_name))
        push_code = repo.push(GITLAB_TOKEN)
        if not push_code:
            raise Exception("push error!")
        logger.info("推送成功！")
        # logger.info("开始调用接口自测！")
        # req_code = self.req_url()
        # if not req_code:
        #     raise Exception("测试不通过，无法合入master！")
        # logger.info("自测通过！开始合入gitlab master！")
        repo.pull(GITLAB_TOKEN)
        repo.change_to_branch("master")
        merge_code = repo.merge_master(branch_name, GITLAB_TOKEN)
        if not merge_code:
            raise Exception("合入master失败！")
        logger.info("代码成功合入master！")



if __name__ == '__main__':
    sh = Synchronous()
    sh.run()



